package com.lovo.csc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.csc.dto.ExpenseDto;
import com.lovo.csc.entity.Discount;
import com.lovo.csc.entity.Prepay;
import com.lovo.csc.entity.PrepayRecord;
import com.lovo.csc.mapper.PrepayRecordMapper;
import com.lovo.csc.service.IDiscountService;
import com.lovo.csc.service.IPrepayRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.csc.service.IPrepayService;
import com.lovo.remoteservice.IPayService;
import com.lovo.sscweb.dto.OrderDto;
import com.lovo.util.MQUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * <p>
 * 客户预存款消费的记录 服务实现类
 * </p>
 *
 * @author lovo
 * @since 2022-07-07
 */
@Service
public class PrepayRecordServiceImpl extends ServiceImpl<PrepayRecordMapper, PrepayRecord> implements IPrepayRecordService {
    @Autowired
    IPrepayRecordService service;
    @Autowired
    IPrepayService prepayService;
    @Autowired
    IDiscountService discountService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    IPayService payService;
    @RabbitListener(queues = MQUtil.ORDERQUEUE1)
    public void orderDead(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, String order) throws IOException {
        if (order == null){
            return;
        }
        OrderDto orderDto =JSON.parseObject(order,OrderDto.class);
        String userCode = orderDto.getUsername();
        double total= orderDto.getOrderTotal();

        QueryWrapper<Prepay> prepayQueryWrapper= new QueryWrapper<>();
        prepayQueryWrapper.eq("user_code",userCode);
        Prepay prepay=prepayService.getOne(prepayQueryWrapper);
        if (prepay==null){
//            redisTemplate.opsForHash().delete("order",JSON.toJSONString(orderDto));
            channel.basicAck(tag,true);
            return;
        }

        //查看会员拥有的折扣率
        QueryWrapper<Discount> discountQueryWrapper= new QueryWrapper<>();
        discountQueryWrapper.eq("membership",prepay.getUserGrade());
        Discount discount = discountService.getOne(discountQueryWrapper);
        double afterDiscount = total * discount.getDiscountRate();
        // 余额不足
        if (afterDiscount > prepay.getBalance()){
            rabbitTemplate.convertAndSend(MQUtil.PrepayExchange,"expenditure.key",JSON.toJSONString(orderDto));//王晓亮
            channel.basicAck(tag,true);
            return;
        }
        // 打折后消费的金额
        orderDto.setPayPrice(afterDiscount);
        orderDto.setOrderStatus(1);
        orderDto.setMethodPayment(0);
        orderDto.setDiscount(discount.getDiscountRate());
        rabbitTemplate.convertAndSend(MQUtil.PrepayExchange,"expenditure.key",JSON.toJSONString(orderDto));//王晓亮
        // 成功通知  通知人员
        rabbitTemplate.convertAndSend(MQUtil.PrepayExchange,"inform.key",orderDto);//卢红兵
        // 用户余额减去消费金额
        prepay.setBalance((prepay.getBalance() - afterDiscount));
        prepayService.saveOrUpdate(prepay);

        payService.consumption(userCode, (float) afterDiscount,orderDto.getOrderCode());
        // 调用支付系统接口
//        payService.consumption(userCode,(float) afterDiscount,orderDto.getOrderType());
        // 通知前端x
        ExpenseDto expenseDto = new ExpenseDto();
        expenseDto.setUserName(userCode);
        expenseDto.setMoney((float) afterDiscount);
        rabbitTemplate.convertAndSend(MQUtil.PrepayExchange,"expense.key",expenseDto);
        // 删除缓存中本次已处理的审核
//        redisTemplate.opsForHash().delete("order",orderCode);
        //这里保存预存款的消费记录
        PrepayRecord prepayRecord = new PrepayRecord();
        prepayRecord.setPrepayId(prepay.getPrepayId());
        prepayRecord.setRecordTime(orderDto.getPlaOrderTime());
        prepayRecord.setBalance(prepay.getBalance());
        prepayRecord.setMoney( afterDiscount);
        prepayRecord.setFkOrder(orderDto.getOrderCode());
        prepayRecord.setUserCode(userCode);
        service.save(prepayRecord);

//        redisTemplate.opsForHash().put("order",orderDto.getOrderCode(),orderDto);
        channel.basicAck(tag,true);
    }


}
